﻿using Learun.Application.Base.SystemModule;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;

namespace Learun.Application.Web.AppApi
{
    /// <summary>
    /// 数据字典接口（dataitem和dataitemdetail）
    /// </summary>
    [RoutePrefix("api/DataItemApi")]
    [HandlerApiLogin(FilterMode.Ignore)]
    public class DataItemApiController : WebApiControllerBase
    {
        private DataItemIBLL dataItemIBLL = new DataItemBLL();
        private ec_dataitemIBLL ec_dataitemIBLL = new ec_dataitemBLL();

        ///// <summary>
        ///// 根据分类编号获取数据字典明细(公司级）
        ///// </summary>
        ///// <param name="itemCode">分类编号</param>
        ///// <returns></returns>
        //[HttpGet]
        //[ResponseType(typeof(List<DataItemDetailEntity>))]
        //public IHttpActionResult GetCodeList(string itemCode)
        //{
        //    try
        //    {
        //        var data = dataItemIBLL.GetDetailList(itemCode);
        //        return Success(data);
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail(ex.Message);
        //    }
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerApiLogin(FilterMode.Enforce)]
        public IHttpActionResult SaveDetailForm(ec_dataitemdetailEntity strEntity, string ProjectId)
        {
            var tableName = ProjectSugar.TableName<ec_dataitemEntity>(ProjectId);
            var list = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(tableName).Where(x => x.DataItemID == strEntity.DataItemID || x.DataItemCode == strEntity.ItemCode).ToList();
            if (list != null && !string.IsNullOrEmpty(strEntity.DataItemName) && !string.IsNullOrEmpty(strEntity.DataItemCode))
            {
                strEntity.IsEnabled = 1;
                var res = ec_dataitemIBLL.SaveDetailEntity(strEntity.DataItemDetailID, strEntity, ProjectId);

                return Success(res);
            }
            return Fail("分类不存在");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerApiLogin(FilterMode.Enforce)]
        public IHttpActionResult DeleteDetail(string DetailID, string ProjectId)
        {
            ec_dataitemIBLL.DeleteDetail(DetailID, ProjectId);
            return Success("保存成功！");
        }

        /// <summary>
        /// 根据分类编号获取数据字典明细（项目级）
        /// </summary>
        /// <param name="itemCode">分类编号</param>
        /// <param name = "projectId" >项目ID，如果为空就是公司级。</param >
        /// <returns></returns>
        [HttpGet]
        [HandlerApiLogin(FilterMode.Enforce)]
        public IHttpActionResult GetDetails(string projectId, string itemCode)
        {
            try
            {
                if (string.IsNullOrEmpty(projectId))
                {
                    var dataCompanyLevel = dataItemIBLL.GetDetailList(itemCode);
                    return Success(dataCompanyLevel);
                }

                SqlSugarHelper.Db.BeginTran();
                var dataitemTableName = ProjectSugar.TableName<ec_dataitemEntity>(projectId);
                var itemcodes = new List<string>() { "自动化平台", "Be_Signal_Group", "Exten_Alarm_Group", "Alarm_Blocking_Group", "Maker", "Alarm" };
                #region 没有就新增
                var items = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(dataitemTableName).Where(x => itemcodes.Contains(x.DataItemCode)).ToList();
                var upDataItem = items.FirstOrDefault(x => x.DataItemCode == "自动化平台");
                if (upDataItem == null)
                {
                    upDataItem = new ec_dataitemEntity();
                    upDataItem.Create();//DataItemID
                    upDataItem.UpDataItemID = "0";
                    upDataItem.DataItemName = "自动化平台";
                    upDataItem.DataItemCode = "自动化平台";
                    upDataItem.OrderID = 6;
                    upDataItem.IsEnabled = 1;
                    upDataItem.IsAllowEdit = 1;
                    SqlSugarHelper.Db.Insertable(upDataItem).AS(dataitemTableName).ExecuteCommand();
                }
                if (!items.Any(x => x.DataItemCode == "Be_Signal_Group"))
                {
                    var item = new ec_dataitemEntity();
                    item.Create();
                    item.UpDataItemID = upDataItem.DataItemID;
                    item.DataItemName = "信号分组";
                    item.DataItemCode = "Be_Signal_Group";
                    item.OrderID = 1;
                    item.IsEnabled = 1;
                    item.IsAllowEdit = 1;
                    SqlSugarHelper.Db.Insertable(item).AS(dataitemTableName).ExecuteCommand();
                }
                if (!items.Any(x => x.DataItemCode == "Exten_Alarm_Group"))
                {
                    var item = new ec_dataitemEntity();
                    item.Create();
                    item.UpDataItemID = upDataItem.DataItemID;
                    item.DataItemName = "延伸报警组";
                    item.DataItemCode = "Exten_Alarm_Group";
                    item.OrderID = 2;
                    item.IsEnabled = 1;
                    item.IsAllowEdit = 1;
                    SqlSugarHelper.Db.Insertable(item).AS(dataitemTableName).ExecuteCommand();
                }
                if (!items.Any(x => x.DataItemCode == "Alarm_Blocking_Group"))
                {
                    var item = new ec_dataitemEntity();
                    item.Create();
                    item.UpDataItemID = upDataItem.DataItemID;
                    item.DataItemName = "报警阻断组";
                    item.DataItemCode = "Alarm_Blocking_Group";
                    item.OrderID = 4;
                    item.IsEnabled = 1;
                    item.IsAllowEdit = 1;
                    SqlSugarHelper.Db.Insertable(item).AS(dataitemTableName).ExecuteCommand();
                }
                if (!items.Any(x => x.DataItemCode == "Maker"))
                {
                    var item = new ec_dataitemEntity();
                    item.Create();
                    item.UpDataItemID = upDataItem.DataItemID;
                    item.DataItemName = "厂商";
                    item.DataItemCode = "Maker";
                    item.OrderID = 10;
                    item.IsEnabled = 1;
                    item.IsAllowEdit = 1;
                    SqlSugarHelper.Db.Insertable(item).AS(dataitemTableName).ExecuteCommand();
                }
                if (!items.Any(x => x.DataItemCode == "Alarm"))
                {
                    var item = new ec_dataitemEntity();
                    item.Create();
                    item.UpDataItemID = upDataItem.DataItemID;
                    item.DataItemName = "报警";
                    item.DataItemCode = "Alarm";
                    item.OrderID = 6;
                    item.IsEnabled = 1;
                    item.IsAllowEdit = 1;
                    SqlSugarHelper.Db.Insertable(item).AS(dataitemTableName).ExecuteCommand();
                }
                #endregion
                if (itemCode == "Be_Signal_Group")
                {
                    var tableName = ProjectSugar.TableName<ec_Wire_GroupEntity>(projectId);
                    //数据字典
                    var groups = SqlSugarHelper.Db.Queryable<ec_Wire_GroupEntity>().AS(tableName)
                        .Where(x => !string.IsNullOrEmpty(x.Signal_Group))
                        .GroupBy(x => x.Signal_Group).Select(x => x.Signal_Group).ToList();//这里可能为空的,因为现在虚拟点也在这里
                    var dataitemDetailTableName = ProjectSugar.TableName<ec_dataitemdetailEntity>(projectId);
                    var item = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(dataitemTableName).First(x => x.DataItemCode == "Be_Signal_Group");
                    if (item == null)
                    {
                        item = new ec_dataitemEntity();
                        item.Create();
                        item.UpDataItemID = "0";
                        item.DataItemName = "信号分组";
                        item.DataItemCode = "Be_Signal_Group";
                        item.OrderID = 5;
                        item.IsEnabled = 1;
                        SqlSugarHelper.Db.Insertable(item).AS(dataitemTableName).ExecuteCommand();
                    }
                    var list = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(dataitemDetailTableName)
                        .Where(x => x.DataItemID == item.DataItemID && groups.Contains(x.DataItemCode)).ToList();
                    var details = new List<ec_dataitemdetailEntity>();
                    var max = list.Max(x => x.OrderID);
                    groups.ForEach(x =>
                    {
                        if (!list.Any(y => y.DataItemID == item.DataItemID && y.DataItemCode == x))
                        {
                            var detail = new ec_dataitemdetailEntity();
                            detail.Create();
                            detail.DataItemID = item.DataItemID;
                            detail.UpDataItemDetailID = "0";
                            detail.DataItemName = "excel导入时新增，请编辑其正确含义";
                            detail.DataItemCode = x;
                            detail.OrderID = ++max;
                            detail.IsEnabled = 1;

                            details.Add(detail);
                        }
                    });
                    SqlSugarHelper.Db.Insertable(details).AS(dataitemDetailTableName).ExecuteCommand();
                }//遍历信号里的组，如果没有就加枚举
                SqlSugarHelper.Db.CommitTran();
                var data = ec_dataitemIBLL.GetDetailList(itemCode, "", projectId, false);
                return Success(data);
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// (计量单位)根据计量单位分类ID获取计量单位数据
        /// </summary>
        /// <param name = "projectId" >项目ID</param >
        /// <param name="measuringUnitTypeID">计量单位分类ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(List<ec_measuring_unitEntity>))]
        public IHttpActionResult GetMeasuringUnitList(string projectId, string measuringUnitTypeID)
        {
            try
            {
                //相当于用一个dataitem来查询下面的所有字典详细列表
                var data = new ec_measuring_unitBLL().GetList("{ ProjectId :\"" + projectId + "\",MeasuringUnitTypeID :\"" + measuringUnitTypeID + "\"}");
                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
    }
}